<template>
  <div class="user-profile-container">
    <!-- 用户头部信息 -->
    <div class="user-header">
      <div class="header-bg"></div>
      <div class="user-info">
        <div class="avatar-container">
          <div class="demo-type">
            <el-avatar :size="120"  :src="userInfo.avatarUrl" @error="errorHandler">
              <img src="./public/images/13992.jpg"/>
            </el-avatar>
          </div>
          <div class="user-level">Lv.{{ userLevel }}</div>
        </div>
        <div class="user-main-info">
          <div class="username-container">
            <div class="username">{{ userInfo.username }}</div>
            <div class="user-badge">{{ userInfo.genderDesc }}</div>
          </div>
          <div class="user-signature">
            {{ userInfo.bio || '这个人很懒，什么都没有留下...' }}
          </div>
          <div class="user-stats">
            <div class="stat-item" @click="showFollowDialog('following')">
              <div class="stat-value">{{ formatNumber(userInfo.followingCount) }}</div>
              <div class="stat-label">关注</div>
            </div>
            <div class="stat-item" @click="showFollowDialog('follower')">
              <div class="stat-value">{{ formatNumber(userInfo.followerCount) }}</div>
              <div class="stat-label">粉丝</div>
            </div>
            <div class="stat-item" @click="activeTab = 'likes'">
              <div class="stat-value">{{ formatNumber(userInfo.followerCount) }}</div>
              <div class="stat-label">获赞</div>
            </div>
          </div>
          <div class="user-actions" v-if="userInfo.userId != id">
            <button class="action-btn follow-btn" @click="toggleFollow">
              {{ isFollowing ? '已关注' : '关注' }}
            </button>
            <button class="action-btn message-btn">
              发消息
            </button>
          </div>
          <el-button style="float: right; margin-top: 10px" type="primary" @click="handleAdd">
            <i class="el-icon-plus"></i> 发布新闻
          </el-button>
        </div>
      </div>
    </div>
<!--    关注/粉丝列表-->
    <el-dialog
        :title="dialogTitle"
        :model-value="followDialogVisible"
        width="60%"
        :before-close="handleClose"
    >
      <el-empty v-if="userList.length === 0" description="暂无数据"></el-empty>
      <div class="userList-info" v-for="user in userList" :key="user.userId">
        <div class="avatar-container">
          <div class="demo-type">
            <el-avatar :size="50"  :src="user.avatarUrl" @error="errorHandler">
              <img src="./public/images/13992.jpg"/>
            </el-avatar>
          </div>
        </div>
        <div class="user-main-info">
          <div class="username-container">
            <div class="username" style="font-size: 18px">{{ user.username }}</div>
          </div>
          <div class="user-signature">
            {{ user.bio || '这个人很懒，什么都没有留下...' }}
          </div>

        </div>
      </div>
<!--      <common-pagination-->
<!--          :activeTab = 'follow'-->
<!--          :pagination="followPagination"-->
<!--          @page-change="handlePageChange"-->
<!--      />-->

    </el-dialog>
    <!-- 内容标签页 -->
    <el-tabs v-model="activeTab" class="content-tabs">

      <el-tab-pane label="历史观看" name="history">
        <div v-if="historyContents.length > 0" class="content-grid">
          <div v-for="(item, index) in historyContents"
               :key="index" class="content-card"
               @click="handleCardClick(item.contentId)"
               style="cursor: pointer;">
            <div class="card-info">
              <div class="card-header">
                <div class="card-title">{{ item.title }}</div>
                <div class="card-summary">{{ item.summary }}</div>
              </div>
              <div class="card-meta">
                <span>{{ this.userInfo.username }}</span>
                <span>{{ formatDate(item.publishTime) }}</span>
              </div>

              <div class="card-actions">
                <el-button type="text" icon="el-icon-chat-line-round">
                  {{ formatNumber(item.likeCount) }}
                </el-button>
                <el-button type="text" icon="el-icon-chat-line-round">
                  {{ formatNumber(item.readCount) }}
                </el-button>
              </div>

            </div>
          </div>
        </div>
        <div v-else class="empty-content">
          <i class="el-icon-tickets empty-icon"></i>
          <p>暂无历史观看记录</p>
        </div>
        <common-pagination
            v-if="activeTab === 'history'"
            :pagination="historyPagination"
            @page-change="handlePageChange"
        />

      </el-tab-pane>

      <el-tab-pane label="我的收藏" name="favorites" >
        <div v-if="favoriteContents.length > 0" class="content-grid">
          <div v-for="(item, index) in favoriteContents"
               :key="index" class="content-card"
               @click="handleCardClick(item.contentId)"
               style="cursor: pointer;">
            <div class="card-info">
              <div class="card-header">
                <div class="card-title">{{ item.title }}</div>
                <div class="card-summary">{{ item.summary }}</div>
              </div>
              <div class="card-meta">
                <span>{{ item.username }}</span>
                <span>{{ formatDate(item.publishTime) }}</span>
              </div>

              <div class="card-actions">
                <el-button type="text" icon="el-icon-chat-line-round">
                  {{ formatNumber(item.likeCount) }}
                </el-button>
                <el-button type="text" icon="el-icon-chat-line-round">
                  {{ formatNumber(item.readCount) }}
                </el-button>
              </div>

            </div>
          </div>
        </div>

        <div v-else class="empty-content">
          <i class="el-icon-star-off empty-icon"></i>
          <p>暂未收藏内容</p>
        </div>
        <common-pagination
            v-if="activeTab === 'favorites'"
            :pagination="favoritesPagination"
            @page-change="handlePageChange"
        />
      </el-tab-pane>

      <el-tab-pane label="我的作品" name="mycontents" >
        <div v-if="publishContent.length > 0" class="content-grid">
          <div v-for="(item, index) in publishContent"
               :key="index" class="content-card"
               @click="handleCardClick(item.contentId)"
               style="cursor: pointer;">
            <div class="card-info">
              <div class="card-header">
                <div class="card-title">{{ item.title }}
                  <el-tag :type="getStatusTagType(item.statusCode)">
                    {{ item.statusCode == 1 ? '草稿' : (item.statusCode == 2 ? '审核中' : '已发布')}}
                  </el-tag></div>
                <div class="card-summary">{{ item.summary }}</div>
              </div>
              <div class="card-meta">
                <span>{{ this.userInfo.username }}</span>
                <span>{{ formatDate(item.publishTime) }}</span>
              </div>

              <div class="card-actions">
                <el-button type="text" icon="el-icon-chat-line-round">
                  {{ formatNumber(item.likeCount) }}
                </el-button>
                <el-button type="text" icon="el-icon-chat-line-round">
                  {{ formatNumber(item.readCount) }}
                </el-button>
              </div>

            </div>
          </div>
        </div>
        <div v-else class="empty-content">
          <i class="el-icon-star-off empty-icon"></i>
          <p>暂未发布内容</p>
        </div>
        <common-pagination
            v-if="activeTab === 'mycontents'"
            :pagination="publishPagination"
            @page-change="handlePageChange"
        />

      </el-tab-pane>

      <el-tab-pane label="个人资料" name="profile">
        <div style="padding: 30px;">
          <el-descriptions title="基本信息" :column="2" border>
            <el-descriptions-item label="用户ID">{{ userInfo.userId }}</el-descriptions-item>
            <el-descriptions-item label="用户名">{{ userInfo.username }}</el-descriptions-item>
            <el-descriptions-item label="性别">{{ userInfo.genderDesc }}</el-descriptions-item>
            <el-descriptions-item label="邮箱">{{ userInfo.email || '未设置' }}</el-descriptions-item>
            <el-descriptions-item label="手机号">{{ userInfo.phone || '未设置' }}</el-descriptions-item>
            <el-descriptions-item label="注册时间">{{ formatDate(userInfo.createTime) }}</el-descriptions-item>
            <el-descriptions-item label="最后登录">{{ formatDate(userInfo.lastLoginTime) }}</el-descriptions-item>
            <el-descriptions-item label="个人简介" :span="2">{{ userInfo.bio || '暂无简介' }}</el-descriptions-item>
          </el-descriptions>
          <el-button style="float: right; margin: 10px 0" type="primary" @click="handleEdit">
            <i class="el-icon-plus"></i> 编辑信息
          </el-button>
        </div>
      </el-tab-pane>

      <!-- 修改个人信息弹窗 -->
      <el-dialog v-model="editProfileDialog" title="修改个人信息" width="50%" center>
        <el-form ref="editForm" :model="editForm" :rules="editRules" label-width="100px">
<!--          <el-form-item label="头像" prop="avatar">-->
<!--            <el-upload-->
<!--                class="avatar-uploader"-->
<!--                action="#"-->
<!--                :show-file-list="false"-->
<!--                :on-success="handleAvatarSuccess"-->
<!--                :before-upload="beforeAvatarUpload"-->
<!--            >-->
<!--              <img v-if="editForm.avatarUrl" :src="editForm.avatarUrl" class="avatar">-->
<!--              <i v-else class="el-icon-plus avatar-uploader-icon"></i>-->
<!--            </el-upload>-->
<!--          </el-form-item>-->

          <el-form-item label="用户名" prop="username">
            <el-input v-model="editForm.username" placeholder="请输入用户名"></el-input>
          </el-form-item>

          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="editForm.genderCode">
              <el-radio :label="1">男</el-radio>
              <el-radio :label="2">女</el-radio>
              <el-radio :label="3">未知</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="手机号" prop="phone">
            <el-input v-model="editForm.phone" placeholder="请输入手机号"></el-input>
          </el-form-item>

          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email" placeholder="请输入邮箱"></el-input>
          </el-form-item>

          <el-form-item label="个人简介" prop="bio">
            <el-input v-model="editForm.bio" type="textarea" rows="4" placeholder="请输入个人简介"></el-input>
          </el-form-item>
        </el-form>
        <template #footer>
        <span class="dialog-footer">
          <el-button @click="editProfileDialog = false">取消</el-button>
          <el-button type="primary" @click="submitEditForm">确认修改</el-button>
        </span>
        </template>
      </el-dialog>
    </el-tabs>

  </div>
</template>

<script>
import axios from '@/utils/request';
import { useAuthStore } from '@/stores/auth'
import CommonPagination from '@/components/CommonPagination.vue'


export default {
  components: {
    CommonPagination,
  },
  data() {
    return {
      followDialogVisible: false,
      dialogTitle: '',
      followingCount: 0,
      followerCount: 0,
      userInfo:{},
      userList: [],
      activeTab: 'history',

      id:useAuthStore().user.id,
      //编辑用户信息
      editProfileDialog: false,
      editForm: {
        userId:'',
        username: '',
        genderCode: 1,
        phone: '',
        email: '',
        bio: '',
        avatarUrl: ''
      },
      editRules: {
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        genderCode: [{ required: true, message: '请选择性别', trigger: 'change' }],
        phone: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }],
        email: [{ type: 'email', message: '请输入正确的邮箱', trigger: 'blur' }]
      },
      isFollowing: false,
      followPagination:{
        currentPage: 1,
        pageSize: 3,
        total: 0
      },
      // 历史观看数据
      historyContents: [],
      historyPagination: {
        currentPage: 1,
        pageSize: 3,
        total: 0
      },
      // 收藏数据
      favoriteContents: [],
      favoritesPagination: {
        currentPage: 1,
        pageSize: 3,
        total: 0
      },
      // 发布数据
      publishContent: [],
      publishPagination: {
        currentPage: 1,
        pageSize: 3,
        total: 0
      },
    }
  },
  computed: {
    userLevel() {
      // 根据用户活跃度计算等级
      const level = Math.floor(this.userStats.likes / 1000) + 1;
      return Math.min(level, 6);
    }
  },
  created() {
    this.getUserInfo()
    this.getContentsByUserIdPage()
    this.getContentByFavorites()
    this.getHistoryContents()
  },
  methods: {
    //获取用户信息
    getUserInfo() {
      console.log(useAuthStore().user.id)
      axios.get(`/users/info/${useAuthStore().user.id}`).then(response => {
        if (response.data.code === 200) {
          this.userInfo = response.data.data;
        } else {
          this.$message.error('获取用户信息失败');
        }
      })
    },
    showFollowDialog(type) {
      this.dialogTitle = type === 'following' ? '关注列表' : '粉丝列表'
      // const params = {
      //   current: this.followPagination.currentPage,
      //   size: this.followPagination.pageSize
      // };
      let url = null
      if(type === 'following'){
        url = `/user/getFollowing/${useAuthStore().user.id}`
      }else {
        url = `/user/getFollower/${useAuthStore().user.id}`
      }
      axios.get(url).then(response => {
        if (response.data.code === 200) {
          this.userList = response.data.data.records;
          this.followPagination.total = response.data.data.total;
        } else {
          this.$message.error('获取粉丝列表失败');
        }
      })
      this.followDialogVisible = true
    },
    // 关闭弹窗前的处理
    handleClose() {
      this.followDialogVisible = false;
    },

    // 分页
    handlePageChange(page) {
      switch (this.activeTab) {
        case 'history':
          this.historyPagination.currentPage = page;
          this.getHistoryContents();
          break;
        case 'favorites':
          this.favoritesPagination.currentPage = page;
          this.getContentByFavorites();
          break;
        case 'mycontents':
          this.publishPagination.currentPage = page;
          this.getContentsByUserIdPage();
          break;
        case 'follow':
          this.followPagination.currentPage = page;
          this.getContentsByUserIdPage();
          break;
      }
    },
    // 获取用户发布的内容（分页）
    getContentsByUserIdPage() {
      const params = {
        current: this.publishPagination.currentPage,
        size: this.publishPagination.pageSize
      };

      axios.get(`/contents/getContentsByUserIdPage/${useAuthStore().user.id}`, {params}).then(response => {
        if (response.data.code === 200) {
          this.publishContent = response.data.data.records;
          this.publishPagination.total = response.data.data.total;
        } else {
          this.$message.error('获取内容失败');
        }
      }).catch(error => {
        this.$message.error('请求出错');
        console.error(error);
      });
    },

    // 获取用户收藏的内容（分页）
    getContentByFavorites() {
      const params = {
        current: this.favoritesPagination.currentPage,
        size: this.favoritesPagination.pageSize,
      };

      axios.get(`/contents/getContentByFavorites/${useAuthStore().user.id}`, {params}).then(response => {
        if (response.data.code === 200) {
          this.favoriteContents = response.data.data.records;
          this.favoritesPagination.total = response.data.data.total;
        } else {
          this.$message.error('获取内容失败');
        }
      }).catch(error => {
        this.$message.error('请求出错');
        console.error(error);
      });
    },
    // 获取历史观看记录（分页）
    getHistoryContents() {
      const params = {
        current: this.historyPagination.currentPage,
        size: this.historyPagination.pageSize,
        userId: useAuthStore().user.id
      };

      axios.get(`/contents/getHistory/${useAuthStore().user.id}`, {params}).then(response => {
        if (response.data.code === 200) {
          this.historyContents = response.data.data.records;
          this.historyPagination.total = response.data.data.total;
        } else {
          this.$message.error('获取历史记录失败');
        }
      }).catch(error => {
        this.$message.error('请求出错');
        console.error(error);
      });
    },
    handleAdd() {
      this.$router.push(`/addContent`);
    },
    // 获取状态标签类型
    getStatusTagType(statusCode) {
      const map = {
        3: 'success', // 已发布
        2: 'warning', // 待审核
        1: 'info'   // 草稿
      };
      return map[statusCode] || 'info';

  },
    // 处理卡片点击事件
    handleCardClick (contentId){
      this.$router.push(`/content/${contentId}`);
    },
    // 编辑信息
    handleEdit(){
      this.editForm = {
        userId:this.userInfo.userId,
        avatarUrl: this.userInfo.avatarUrl || '',
        username: this.userInfo.username,
        genderCode: this.userInfo.genderCode || '未知',
        phone: this.userInfo.phone || '',
        email: this.userInfo.email || '',
        bio: this.userInfo.bio || ''
      }
      this.editProfileDialog = true
    },

    // 修改个人信息
    submitEditForm() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          axios.post(`/users/updateById`, this.editForm).then(response => {
            if (response.data.code === 200) {
              this.$message.success('修改成功');
              this.editProfileDialog = false;
              // 重新获取用户信息
              this.getUserInfo()
            } else {
              this.$message.error(response.data.message || '修改失败');
            }
          }).catch(error => {
            console.error('修改个人信息失败', error);
            this.$message.error('修改失败，请稍后再试');
          });
        } else {
          console.log('验证失败');
          return false;
        }
      });
    },
    errorHandler() {
      return true
    },
    formatNumber(num) {
      if (num >= 10000) {
        return (num / 10000).toFixed(1) + '万';
      }
      return num;
    },
    //日期格式
    formatDate(dateStr) {
      if (!dateStr) return '-';
      const date = new Date(dateStr);
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    },

    //关注（待定）
    toggleFollow() {
      this.isFollowing = !this.isFollowing;
      this.$message({
        message: this.isFollowing ? '关注成功！' : '已取消关注',
        type: this.isFollowing ? 'success' : 'info'
      });
    },
  }
}

</script>
<style>
.user-profile-container {
  width: 100%;
  margin: 20px auto;
  padding: 0 20px;
}
.user-header {
  background: linear-gradient(135deg, #00a1d6 0%, #0080b0 100%);
  border-radius: 8px;
  padding: 30px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  color: white;
  position: relative;
  overflow: hidden;
  margin-bottom: 20px;
}
.header-bg {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url('https://picsum.photos/1200/300?grayscale');
  background-size: cover;
  background-position: center;
  opacity: 0.15;
  z-index: 0;
}
.user-info {
  position: relative;
  z-index: 1;
  display: flex;
  align-items: center;
}
.userList-info{
  position: relative;
  z-index: 1;
  display: flex;
  align-items: center;
  border-bottom: 1px solid #bae7ff;

}
.userList-info:hover{
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.avatar-container {
  position: relative;
  margin-right: 30px;
}

.user-level {
  position: absolute;
  bottom: 0;
  right: 0;
  background: linear-gradient(135deg, #ff9500 0%, #ff5000 100%);
  color: white;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  border: 2px solid white;
  font-size: 14px;
}
.user-main-info {
  flex: 1;
}
.username-container {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}
.username {
  font-size: 28px;
  font-weight: bold;
  margin-right: 15px;
}
.user-badge {
  background: rgba(255, 255, 255, 0.2);
  border-radius: 4px;
  padding: 4px 10px;
  font-size: 14px;
  margin-right: 10px;
}

.user-signature {
  font-size: 16px;
  margin-bottom: 20px;
  max-width: 600px;
  opacity: 0.9;
}
.user-stats {
  display: flex;
  gap: 30px;
  margin-top: 15px;
}
.user-actions {
  display: flex;
  gap: 15px;
  margin-top: 25px;
}
.action-btn {
  padding: 8px 20px;
  border-radius: 20px;
  border: none;
  cursor: pointer;
  font-weight: bold;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s;
}
.follow-btn {
  background: linear-gradient(135deg, #fb7299 0%, #ff4d7c 100%);
  color: white;
}
.follow-btn:hover {
  background: linear-gradient(135deg, #e66187 0%, #e63d6d 100%);
  box-shadow: 0 4px 12px rgba(251, 114, 153, 0.4);
}
.message-btn {
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border: 1px solid rgba(255, 255, 255, 0.4);
}
.message-btn:hover {
  background: rgba(255, 255, 255, 0.3);
}
.stat-item {
  text-align: center;
  cursor: pointer;
  transition: all 0.3s;
}
.stat-item:hover {
  transform: translateY(-3px);
}
.stat-value {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 5px;
}
.stat-label {
  font-size: 14px;
  opacity: 0.8;
}

.content-tabs {
  background: white;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  overflow: hidden;
}
.content-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
  padding: 20px;
}
.content-card {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
  background: white;
  height: 200px;
}
.content-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(0, 0, 0, 0.1);
}
.card-thumbnail {
  width: 100%;
  height: 160px;
  object-fit: cover;
}
.card-info {
  padding: 15px;
  display: flex;
  flex-direction: column;
  height: 100%; /* Ensure the card takes full height */
}

.card-meta {
  display: flex;
  justify-content: space-between;
  color: var(--el-text-color-placeholder);
  font-size: 14px;
  margin-bottom: 10px;
  align-items: center;
  margin-top: auto;
}

.card-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 10px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;

}

.card-actions {
  display: flex;
  gap: 10px;

}
.card-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: auto;
  padding: 8px 0;

}
.card-stats {
  display: flex;
  justify-content: space-between;
  font-size: 13px;
  color: #999;
}
.stat-icon {
  margin-right: 4px;
}
.empty-content {
  text-align: center;
  padding: 60px 20px;
  color: #999;
}
.empty-icon {
  font-size: 60px;
  margin-bottom: 20px;
  color: #ddd;
}
.section-title {
  font-size: 20px;
  font-weight: bold;
  margin: 30px 0 20px;
  padding-left: 10px;
  border-left: 4px solid #00a1d6;
}

.card-summary {
  font-size: 13px;
  color: #666;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;

}


</style>
